import json
from datetime import datetime

from db.AutoConfigDB import get_config
from db.AutoWordsDB import save_word, get_word_by_word, save_or_update_word
from openai import OpenAI

# 输出格式声明字段
response_format_prouce = """
    请按照json格式输出: 
    {
        "word": "China",
        "pronunciation": "/ˈtʃaɪ.nə/",
        "meaning": "中国"
    }
    """

def query_word(word):
    # 先从数据库查询
    word_info = get_word_by_word(word)
    if word_info is not None:
        return word_info
    else:
        # 从大模型查询
        result = get_trans_result(word)
        if result is not None:
            # 保存到数据库
            word_info = save_word(
                word,
                result["pronunciation"],
                result["meaning"],
                result["costs"]
            )
            return word_info
        else:
            return None


def get_trans_result(word):
    # 读取本地大模型配置
    address = get_config("llm_base_url")
    key = get_config("llm_api_key")
    model = get_config("llm_model")
    # 判断是否有配置
    result = None
    if address is None or key is None or model is None:
        return result
    # 创建openai
    try:
        # 起始时间
        starttime = datetime.now()
        client = OpenAI(
            api_key=key,
            base_url=address
        )
        prompt = f"""
        帮我把英文单词 {word} 翻译为中文并给出读音。最终返回一个 json 格式的数据，
        {response_format_prouce}
        """
        # 获取翻译结果
        response = client.chat.completions.create(
            model=model,
            messages=[
                {"role": "system", "content": "你是一个英文到中文的翻译助手"},
                {"role": "user", "content": prompt}
            ],
            response_format={"type": "json_object"}
        )
        # 结束时间
        endtime = datetime.now()
        # 返回翻译结果
        result = json.loads(response.choices[0].message.content)
        print(result)
        result["costs"] = str(endtime - starttime)
    except Exception as e:
        print(e)
    return result


if __name__ == '__main__':
    print(get_trans_result("ROLLBACK"))
